var fs = require('fs')
var path = require('path')
var mkdirp = require('mkdirp')
var rimraf = require('rimraf')
var PSD = require('psd')
var yargs = require('yargs')

var argv = yargs.usage('Usage: $0 [options] <path>')
    .help('help')
    .alias('h', 'help')
    .option('t', {
      alias: 'text',
      describe: '是否屏蔽text节点，默认不屏蔽',
      type: 'boolean',
      default: false
    })
    .option('c', {
      alias: 'class',
      describe: '输出节点class名称',
      default: 'p-psd'
    })
    .option('s', {
      alias: 'size',
      describe: '文字输出长度过滤，默认输出大于10的文字',
      type: 'number',
      default: 5
    })
    .option('l', {
      alias: 'log',
      describe: '是否屏蔽日志,默认不屏蔽',
      type: 'boolean',
      default: false
    })
    .epilog('enjoy it!')
    .argv;

if(yargs.argv._.length == 0){
  yargs.showHelp()
  process.exit(1)
}
var psdFile = yargs.argv._[0]
var psdFileParse = path.parse(psdFile)
var imgDir = path.resolve(psdFileParse.dir, 'images', psdFileParse.name)
var argv = yargs.argv

var psd = PSD.fromFile(psdFile)
psd.parse();

rimraf.sync(imgDir)

var html = '<!DOCTYPE html>\n<html>\n\t<head><meta charset="utf-8">\n\t\t<style>.'+argv.c+'{position:absolute;}</style>\n\t</head>\n\t<body>'
var imgs = [], txts = []
psd.layers.forEach(item => {
  if(item.isFolder()) return false
  // png parse
  var ipath
  if(item.name.match(/(.*\/)?(.*\.png)$/)){
    !argv.l && console.log('img: '+item.name)
    ipath = path.parse(path.resolve(imgDir, item.name))
    if(!fs.exists(ipath.dir)){
      mkdirp.sync(ipath.dir)
    }
    imgs.push('<img class="'+argv.c+'" style="width:'+item.width+'px;height:'+item.height+'px;left:'+item.left+'px;top:'+item.top+'px;" src="'+path.join('images', psdFileParse.name, item.name)+'">')
    item.image.saveAsPng(path.join(ipath.dir, ipath.base))
  //text parse
  }else if(!argv.t && item.typeTool){
    var textInfo = item.typeTool()
    if(textInfo.textValue.length<=argv.s) return false
    !argv.l && console.log('txt: '+item.name)
    var color = textInfo.colors()[0]
    var size = textInfo.sizes()
    size = size ? size[0] : 12
    color = color[0].toString(16)+color[1].toString(16)+color[2].toString(16)
    txts.push('<div class="'+argv.c+'" style="font-size:'+size+'px;color:#'+color+';width:'+item.width+'px;height:'+item.height+'px;left:'+item.left+'px;top:'+item.top+'px;">'+textInfo.textValue+'</div>')
  }
})
html+=imgs.concat(txts).join('\n\t\t')
html+='\n\t</body>\n</html>'
fs.writeFileSync(path.resolve(psdFileParse.dir, psdFileParse.name+'.html'), html)
